<template>
  <ContentWrap shadow="never">
    <template #header>
      <CardTitle title="服务商列表" />
    </template>
    <div class="mb-4">
      <el-alert type="warning" :closable="false">
        <template #title>
          <div class="items-center gap-2">
            <h4>服务商后台登录地址：</h4>
            <div class="flex url_cory items-center gap-2">
              <span class="urlCurrnet">{{ agentH5Url }}</span>
              <el-button type="warning" size="small" @click="copyUrl">复制</el-button>
            </div>
          </div>
        </template>
      </el-alert>
    </div>
    <el-form :inline="true" :model="queryParams" class="demo-form-inline mb-4">
      <el-form-item label="服务商：">
        <el-input
          v-model.trim="queryParams.nameOrMobile"
          style="width: 200px"
          placeholder="请输入手机号码或者姓名"
          clearable
        />
      </el-form-item>
      <el-form-item label="选择代理商" prop="agentId">
        <el-select
          v-model="queryParams.agentId"
          placeholder="请选择代理商"
          clearable
          filterable
          remote
          :loading="agentLoading"
          :remote-method="searchAgent"
          style="width: 240px"
        >
          <el-option
            v-for="agent in agentOptions"
            :key="agent.id || agent.agentId"
            :label="`${agent.agentName || agent.name} ${agent.mobile ? '(' + agent.mobile + ')' : ''}`"
            :value="agent.id || agent.agentId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="成为服务商时间：">
        <el-date-picker
          v-model="queryParams.date"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          @change="handleDateChange"
          class="!w-240px"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">搜索</el-button>
        <!-- <el-button @click="resetQuery">重置</el-button> -->
        <el-button type="primary" @click="handleAdd">新增服务商</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
  <ContentWrap>
    <el-table
      :data="showDataList"
      v-loading="agentloading"
      :stripe="true"
      :show-overflow-tooltip="true"
    >
      <el-table-column prop="name" label="服务商名称" align="center" />
      <el-table-column prop="agentId" label="代理商编号" align="center" />
      <el-table-column prop="agentName" label="代理商名称" align="center" />
      <el-table-column prop="contactPhone" label="服务商联系方式" align="center" />
      <el-table-column label="成为服务商时间" align="center">
        <template #default="scope">
          {{ formateDateday(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="到期时间" align="center">
        <template #default="scope">
          <span>{{ formateDateday(scope.row.expireTime) || '--' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总返利金额" align="center">
        <template #default="scope">
          <span>{{ floatToFixed2(scope.row.totalRebateAmount) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="bindMemberPhone" label="绑定会员" align="center" />
      <el-table-column prop="bindMemberPhone" label="状态" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.enabled ? 'success' : 'danger'" size="small">
            {{ scope.row.enabled ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="action" align="center" label="操作" width="180">
        <!-- 查看 编辑 禁用 调整佣金 业绩统计 相关门店 -->
        <template #default="scope">
          <div class="flex justify-center flex-wrap">
            <el-button type="primary" size="small" link @click="handleEdit(scope.row, 'edit')"
              >编辑</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              @click="handleEdit(scope.row, 'performance')"
              >查看佣金记录</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getagentList"
    />
  </ContentWrap>
  <AddService
    v-model="dialogVisible"
    :type="editType"
    @success="handleSuccess"
    :current-row="currentRow"
  />
  <RecordView v-if="recordViewVisible" :id="currentRow.id" @close="recordViewVisible = false" />
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, onMounted, computed, watch, onActivated } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import AddService from './addService.vue'
import { CardTitle } from '@/components/Card'
import RecordView from './recordview.vue'
import { floatToFixed2 } from '@/utils'
import { formateDateday } from '@/utils/formatTime'
import { getAagentUsers } from '@/api/mall/agent/index'
import ServiceApi from '@/api/application/service'

// 定义组件名，便于keep-alive识别
defineOptions({ name: 'AgentManagement' })
const agentH5Url = import.meta.env.VITE_AGENT_URL
// 定义 props
const props = defineProps<{
  info?: any
}>()

// 缓存键名
const CACHE_KEY = 'mall_agent_query_params'

const recordViewVisible = ref(false)
// 声明组件事件

const total = ref(0)
const state = reactive({
  agentloading: false,
  tableData: [] as any,
  dialogVisible: false,
  editType: 'add',
  currentRow: {} as any,
  agentId: 0
})
enum AgentType {
  provincial = 2,
  city = 3,
  district = 4
}

// 枚举反映射
for (let key in AgentType) {
  AgentType[AgentType[key]] = key
}
const { agentloading, tableData, dialogVisible, editType, currentRow } = toRefs(state)
// 记录开始时间
const startDate = ref<Date | null>(null)
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  nameOrMobile: '',
  date: '',
  agentId: undefined as number | undefined
})

const showDataList = computed(() => {
  return tableData.value.map((item: any) => {
    return {
      ...item
    }
  })
})
// 禁用日期
const disabledDate = (time: Date) => {
  const today = new Date()
  today.setHours(23, 59, 59, 999)

  // 禁用未来日期
  if (time.getTime() > today.getTime()) {
    return true
  }

  // 如果已经选择了开始时间，则限制结束时间范围
  if (startDate.value) {
    const maxDate = dayjs(startDate.value).add(3, 'month').toDate()
    return time.getTime() < startDate.value.getTime() || time.getTime() > maxDate.getTime()
  }

  return false
}
const handleSuccess = () => {
  dialogVisible.value = false
  getagentList()
}
const handleEdit = (row: any, type: string) => {
  currentRow.value = row
  switch (type) {
    case 'edit':
      editType.value = 'edit'
      dialogVisible.value = true
      break
    case 'performance':
      recordViewVisible.value = true
      break
  }
}

const agentOptions = ref<any[]>([])
const agentLoading = ref(false)
// 搜索代理商
const searchAgent = async (query: string) => {
  if (!query) {
    agentOptions.value = []
    return
  }

  agentLoading.value = true
  try {
    const res = await getAagentUsers({
      agentName: query,
      pageNo: 1,
      pageSize: 20
    })
    agentOptions.value = res.list || []
  } catch (error) {
    console.error('搜索代理商失败:', error)
    ElMessage.error('搜索代理商失败')
    agentOptions.value = []
  } finally {
    agentLoading.value = false
  }
}
// 新增服务商
const handleAdd = () => {
  editType.value = 'add'
  dialogVisible.value = true
}

// 监听日期变化
const handleDateChange = (val: any) => {
  if (val && val.length === 2) {
    const start = dayjs(val[0])
    const end = dayjs(val[1])
    const diffDays = end.diff(start, 'day')

    if (diffDays > 90) {
      ElMessage.warning('时间范围不能超过3个月')
      queryParams.value.date = ''
    }
  } else {
    startDate.value = val?.[0] || null
  }
}

const copyUrl = async () => {
  const url = document.querySelector('.urlCurrnet') as any
  const urlText = url?.innerHTML
  try {
    await navigator.clipboard.writeText(urlText)
    ElMessage.success('复制成功')
  } catch (err) {
    ElMessage.error('复制失败')
  }
}
const onSubmit = () => {
  queryParams.value.pageNo = 1 // 搜索时重置到第一页
  getagentList()
}
const getagentList = async () => {
  agentloading.value = true
  try {
    const data = {
      pageNo: queryParams.value.pageNo,
      pageSize: queryParams.value.pageSize,
      nameOrMobile: queryParams.value.nameOrMobile,
      agentId: queryParams.value.agentId,
      createTime: queryParams.value.date
    }
    const res = await ServiceApi.getServicePage(data)
    tableData.value = res.list || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取服务商列表出错:', error)
  } finally {
    agentloading.value = false
  }
}

onMounted(() => {
  getagentList()
})

// 组件被keep-alive激活时调用
onActivated(() => {
  console.log('AgentManagement组件被激活')
  // 不需要重新加载数据，keep-alive会保持组件状态
})
</script>

<style scoped lang="scss"></style>
